import React, { useState, useEffect } from 'react';
import { TjFilter, TjHeader } from '@/tjComponents';
import TjTable from '@/pages/ETrade/components/TjTable';
import { columns } from './helper';
import { useSetState } from 'ahooks';
import { getWechatOfficialArticle, queryProvinceList } from './service';
import { Select, DatePicker } from 'antd';
import { HttpCode } from '#/utils/contacts.js';
import { useForm } from 'antd/lib/form/Form';
import _ from 'lodash';
import moment from 'moment';
import { SERVER_URL_OBJ } from '@/../config/urlConfig';
import getImgingL from '@/assets/img/getImging_light.png';
import getImgingD from '@/assets/img/getImging_dark.png';
import getImgingG from '@/assets/img/getImging_gre.png';
import { useThemeChange } from '@/hooks/useThemeChange';
import './index.less';

const { RangePicker } = DatePicker;

const defaultValues = {
  keyWord: '',
  officialAccountList: ['all'],
  date: undefined,
};

const TradingCenterArticleList: React.FC = (props) => {
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [marketsList, setMarketsList] = useState<any[]>([{ label: '全部信息来源', value: 'all' }]);
  const [req, setReq] = useSetState(defaultValues);
  const [loading, setLoading] = useState(false);
  const [dataInfo, setDataInfo] = useState<any>({});
  const [form] = useForm();
  const { theme } = useThemeChange();
  const [domain, setDomain] = useState(SERVER_URL_OBJ.release);

  const init = () => {
    queryProvinceList().then((res: any) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        const list = res.data.map((v: string) => ({
          label: v,
          value: v,
        }));
        setMarketsList(marketsList.concat(list));
      }
    });
  };

  const query = () => {
    setLoading(true);
    const newParams: any = { ...req };
    if (newParams.date) {
      newParams.startDate = newParams.date[0].format('YYYY-MM-DD');
      newParams.endDate = newParams.date[1].format('YYYY-MM-DD');
      delete newParams.date;
    }

    if (newParams.officialAccountList?.includes('all')) {
      newParams.officialAccountList = [];
    }
    getWechatOfficialArticle(newParams)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          setDataSource(res.data);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const changeOfficialAccountList = (val: any[]) => {
    const last = val.slice(-1);
    if (last[0] === 'all') {
      form.setFieldsValue({
        officialAccountList: ['all'],
      });
    } else {
      form.setFieldsValue({
        officialAccountList: _.remove(val, (n: string) => n !== 'all'),
      });
    }
  };

  const onSearch = (values: any) => {
    setReq(values);
  };

  const onReset = (values: any) => {
    setReq(values);
  };

  const showImg = (record: any) => {
    setDataInfo(record);
  };

  const goDetails = (url: string) => {
    window.open(url);
  };

  useEffect(() => {
    init();
    const { CLIENT_ENV } = process.env;
    // @ts-ignore
    if (CLIENT_ENV && SERVER_URL_OBJ[CLIENT_ENV]) {
      // @ts-ignore
      setDomain(SERVER_URL_OBJ[CLIENT_ENV]);
    }
  }, []);

  useEffect(() => {
    query();
  }, [req]);

  return (
    <div className="trading-center-article-list">
      <TjHeader
        left={
          <TjFilter
            defaultValues={defaultValues}
            loading={loading}
            onReset={onReset}
            onSearch={onSearch}
            form={form}
            items={[
              {
                name: 'officialAccountList',
                render: (
                  <Select
                    options={marketsList}
                    style={{ width: 200 }}
                    mode="multiple"
                    onChange={changeOfficialAccountList}
                  />
                ),
              },
              {
                name: 'date',
                render: <RangePicker format={'YYYYMMDD'} allowClear={false} separator={'-'} />,
              },
              {
                name: 'keyWord',
              },
            ]}
          />
        }
      />
      <div className="content">
        <div className="left">
          <div className="table-box">
            <TjTable
              columns={columns({ showImg, goDetails })}
              dataSource={dataSource}
              isLoading={loading}
            />
          </div>
        </div>
        <div className="right">
          <div className="title">查看文章</div>

          {dataInfo && dataInfo.title && (
            <>
              <div className="article-title">{dataInfo.title}</div>
              <div className="title-info">
                信息来源<span>{dataInfo.officialAccount}</span>发布时间
                <span>{moment(dataInfo.updateTime).format('YYYYMMDD HHmmss')}</span>
              </div>
              {dataInfo.image && dataInfo.image !== '404' && (
                <div className="img-box">
                  <img
                    src={`${domain}/annex/annex/downLoadFile/${dataInfo.image}`}
                    alt="img"
                    className="img"
                  />
                </div>
              )}
              {dataInfo.image === '404' && <div>当前文章已失效</div>}
              {!dataInfo.image && (
                <div className="img-box">
                  <img
                    className="not-img"
                    src={theme === 'dark' ? getImgingD : theme === 'gre' ? getImgingG : getImgingL}
                    alt="暂无数据"
                  />
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default TradingCenterArticleList;
